package com.shjzit.loglib;

import android.content.Context;
import android.content.Intent;

import com.shjzit.loglib.db.DatabaseManager;
import com.shjzit.loglib.db.dao.LogDaoHelper;
import com.shjzit.loglib.db.entity.LogEntity;
import com.shjzit.loglib.lib_interface.DynamicParameterPropertiesCallBack;
import com.shjzit.loglib.logservice.LogUploadService;
import com.shjzit.loglib.utils.PrintLog;
import com.shjzit.loglib.utils.StringUtils;
import com.shjzit.loglib.utils.ThreadUtils;

import java.util.List;

/**
 * 建议在 Applocation 中做初始化的操作
 */
public class LogUtils {
    private static LogUtils LOGUTILS = new LogUtils();
    private Context context;
    private DatabaseManager instance;

    private DynamicParameterPropertiesCallBack dynamicParameterPropertiesCallBack;

    private LogUtils() {

    }

    /**
     * 初始化，客户端调用
     *
     * @param context
     */
    public void init(Context context, DynamicParameterPropertiesCallBack dynamicParameterPropertiesCallBack) {
        this.context = context;
        instance = DatabaseManager.getInstance();
        instance.initDatabase(context);
        this.dynamicParameterPropertiesCallBack = dynamicParameterPropertiesCallBack;
        LogUploadService.startService(context);
    }

    public static LogUtils getInstance() {
        return LOGUTILS;
    }

    /**
     * 插入log数据，客户端调用
     * （可能存在数据超长的问题，此方法会分隔日志，10000为分隔点）
     *
     * @param
     */
    public void insertLogs(String content) {
        if (content != null && content.length() > 0) {
            LogUploadService.startService(context);
            ThreadUtils.execute(() -> {
                //插入的日志只有不等于空和长度大于0才会生效
                if (content.length() > 10000) {
                    List<String> strList = StringUtils.getStrList(content, 10000);
                    for (int i = strList.size() - 1; i >= 0; i--) {
                        insertDataBase(strList.get(i));
                    }
                } else {
                    //插入数据库
                    insertDataBase(content);
                }
            });
        }
    }


    /**
     * 插入LOG日志到数据库中
     */
    private synchronized void insertDataBase(String logMsg) {
        LogEntity logEntity = new LogEntity();
        logEntity.setCreateTime(System.currentTimeMillis());
        logEntity.setContent(logMsg);
        LogDaoHelper.insertLogs(logEntity);
        context.sendBroadcast(new Intent("com.jzlog.lib"));
    }


    /**
     * 删除 log 数据,Service 自己调用
     *
     * @param entities
     */
    public void deleteLogs(LogEntity... entities) {
        LogDaoHelper.deleteLogs(entities);
    }

    public List<LogEntity> r() {
        return LogDaoHelper.queryAllLogs();
    }


    public DynamicParameterPropertiesCallBack getListener() {
        return dynamicParameterPropertiesCallBack;
    }

}
